<template>
  <el-card>
    <el-form :inline="true" :model="formInline" style="display: flex">
      <el-form-item>
        <el-input v-model="formInline.roleName" placeholder="名称" />
      </el-form-item>
      <el-form-item style="width: 100px">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="flex:1">
        <el-date-picker
            v-model="during"
            type="daterange"
            range-separator="到"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchRoles()">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-popconfirm title="确认分配角色?" @confirm="addUserRole">
      <template #reference>
        <el-button type="primary">提交</el-button>
      </template>
    </el-popconfirm>
    <el-table  ref="roleTable" :data="roles" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roleId" label="ID" width="100"></el-table-column>
      <el-table-column prop="roleName" label="名称" align="center"></el-table-column>
      <el-table-column prop="description" label="描述" align="center"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 1000, 5000]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { ElMessage, FormRules } from 'element-plus';
import {Role, UserRole} from "@/api/type/model.ts";
import {useRoute, useRouter} from "vue-router";
import {putUserRole, fetchUserRoleList} from "@/api/UserRoleApi.ts";
import {fetchRolePage} from "@/api/RoleApi.ts";

const roles: Role[] = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const multipleSelection = ref<Role[]>([]);
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API);
const roleTable = ref(null);

const route = useRoute();
const router = useRouter();

const userId = route.params.userId

const rules = reactive<FormRules>({
  roleName: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ],
  description: [
    { required: true, trigger: 'blur' },
    { min: 1, max: 100, message: '字数必须为 1 到 100', trigger: 'blur', informType: 'warning' },
  ]
});

const formInline: Role = reactive({});

const during = ref([])

const options = ref([
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]);

const fetchRoles = async () => {
  const response = await fetchRolePage(currentPage.value, pageSize.value, formInline, during.value)
  if(response.code === 200){
    roles.value = response.data.records;
    total.value = response.data.total;
    const res = await fetchUserRoleList(userId)
    if(res.code === 200){
      let roleIds = res.data
      let roleList =roles.value.filter(role => roleIds.includes(role.roleId))
      if(roleList){
        roleList.forEach(role => {
          roleTable.value.toggleRowSelection(role, true);
        })
      }
    }
  }
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchRoles();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchRoles();
};

// 多选
const handleSelectionChange = (val: Role[]) => {
  multipleSelection.value = val;
}

// 提交
const addUserRole = async () => {
  if (multipleSelection.value.length === 0) {
    return ElMessage.error("请先选中！");
  }
  console.log(multipleSelection.value)
  let userRoles: UserRole[] = multipleSelection.value.map((role: Role) => {
    return {
      userId: Number(userId),
      roleId: role.roleId
    }
  });
  const res = await putUserRole(userRoles);
  if(res.code == 200 ){
    router.push("/user/list")
  }
}


fetchRoles();

</script>

<style scoped>
.el-card {
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>

